import pickle
import re
from django.db.models.loading import get_model
from django.db.models.query import QuerySet
from django.shortcuts import get_object_or_404

from tppt.lib import utils

def get_filter_spec(query_set):
	if hasattr(query_set, '_meta_filter'):
		return query_set._meta_filter
	
	where_node=query_set.query.where
	
	ewheres=query_set.query.extra_where
	eparams=query_set.query.extra_params
	
	
	wheres=[]
	params=[]
	
	nwhere, nparams=where_node.as_sql()
	if nwhere:
		wheres.append(nwhere)
		params.extend(nparams)
	wheres.extend(ewheres)
	params.extend(eparams)
	
	if not wheres:
		return ''
	
	return pickle.dumps((wheres, params)) 
	
def apply_filter_spec(query_set, spec):
	if not spec:
		return query_set

	model=query_set.model
	
	match_obj=re.compile('^rf@([^@]*)@(.*)$').match(spec)
	if match_obj:
		fld_name=str(match_obj.group(1))
		fld=model.get_fields_dict()[fld_name]
		target_model=fld.rel.to
		target_key=match_obj.group(2)
		target=get_object_or_404(target_model, pk=target_key)
		return query_set.filter_ref(fld_name, target)
	
	match_obj=re.compile('^mm@([^@]*)@([^@]*)@(.*)$').match(spec)
	if match_obj:
		src_model_name=match_obj.group(1)
		src_model=get_model('data', src_model_name)
		src_key=match_obj.group(3)
		src=get_object_or_404(src_model, pk=src_key)
		field_name=str(match_obj.group(2))
		return query_set.filter_m2m(src, field_name)
	
	wheres, params=pickle.loads(spec.__str__())

	res=query_set.extra(where=wheres, params=params)
	return res


def filter_ref(self, field, target):
	res=self.filter(**{field: target})
	res._meta_filter='rf@%s@%s' % (field, target.pk)
	return res
	
def filter_m2m(self, src, field):
	res=getattr(src, field).all()
	res._meta_filter='mm@%s@%s@%s' % (src.__class__.__name__, field, src.pk)
	return res 		

QuerySet.filter_ref=filter_ref;
QuerySet.filter_m2m=filter_m2m;